// Package middleware 二维码生成模块
package middleware

import (
	"bytes"
	"github.com/skip2/go-qrcode"
	"image"
	"image/png"
	"net/url"
)

// Qrcode 生成二维码
func Qrcode(data string, size int) (Qrcode []byte, err error) {
	data, _ = url.QueryUnescape(data)
	num := 50
	if len(data) > 500 {
		return bytes.NewBuffer(nil).Bytes(), nil
	}
	if len(data) > 200 {
		num = 0
	}
	var byte []byte
	byte, err = qrcode.Encode(data, qrcode.Medium, size+num)
	buffer := bytes.NewBuffer(byte)
	m, _, _ := image.Decode(buffer)
	rgbImg := m.(*image.Paletted)
	subImg := rgbImg.SubImage(image.Rect(num/2, num/2, size+num/2, size+num/2)).(*image.Paletted)
	emptyBuff := bytes.NewBuffer(nil)
	png.Encode(emptyBuff, subImg)
	return emptyBuff.Bytes(), err
}
